//
//  YLYSettingViewController.m
//  iEasyBill
//
//  Created by student on 14-5-12.
//  Copyright (c) 2014年 com.yly16. All rights reserved.
//

#import <MobileCoreServices/MobileCoreServices.h>
#import <MediaPlayer/MediaPlayer.h>
#import "YLYSettingViewController.h"
#import "TestViewController.h"
#import <CommonCrypto/CommonDigest.h>
#import "MBProgressHUD.h"


@interface YLYSettingViewController ()
{
    NSString *input_type;
    UIImagePickerController *ipc;
    BOOL *isImagePic;
    BOOL *isStop;
    BOOL *isGetList;
    NSIndexPath *swithIndexPath;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) MBProgressHUD *hud;
@end

@implementation YLYSettingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    isStop = true;
    isDownload = NO;
    isDelete =  NO;
    isGetList=false;
    isUpload = NO;
    [self.activityView setHidden:YES];
    
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccessed) name:kLoginSuccessed object:[sdkCall getinstance]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginFailed) name:kLoginFailed object:[sdkCall getinstance]];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(analysisResponse:) name:kGetUserInfoResponse object:[sdkCall getinstance]];
    self.arrCgiRequest = [NSMutableArray arrayWithCapacity:1];
    
    self.weiyunOperateArray = [NSMutableArray arrayWithCapacity:3];
    {
        NSArray *arrDownLoadClass = [NSArray arrayWithObjects:[WeiYun_download_photo_GET class],[WeiYun_download_video_GET class],[WeiYun_download_video_GET class], nil];
        NSArray *arrDelClass = [NSArray arrayWithObjects:[WeiYun_delete_photo_GET class], [WeiYun_delete_video_GET class], [WeiYun_delete_music_GET class],nil];
        NSArray *arrThumbClass = [NSArray arrayWithObject:[WeiYun_get_photo_thumb_GET class]];
        [_weiyunOperateArray addObject:arrDownLoadClass];
        [_weiyunOperateArray addObject:arrDelClass];
        [_weiyunOperateArray addObject:arrThumbClass];
    }
    
    self.tableList = [[NSArray alloc]initWithObjects:@"账单类别设置",@"账单账户设置",@"密码设置", nil];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)settingPassWord:(id)sender {
    BOOL isPatternSet = ([[NSUserDefaults standardUserDefaults] valueForKey:kCurrentPattern]) ? YES: NO;
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:swithIndexPath];
    UISwitch *swithView = (UISwitch*)[cell viewWithTag:2];
    if (swithView.on == NO) {
        TestViewController *lockVc = [[TestViewController alloc]init];
		lockVc.infoLabelStatus = InfoStatusNormal;
		[self.navigationController presentViewController:lockVc animated:YES completion:^{
			//
		}];
    }
    else{
        TestViewController *lockVc = [[TestViewController alloc]init];
        lockVc.infoLabelStatus = InfoStatusFirstTimeSetting;
        [self.navigationController presentViewController:lockVc animated:YES completion:^{
            //
        }];
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    return self.tableList.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        static NSString *CellIdentifier = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        User *aUser = [[DatabaseManager shareManager]showUser];
        if (aUser != nil) {
            UIImageView *imageView = (UIImageView*)[cell viewWithTag:1];
            imageView.image = [UIImage imageWithData:aUser.userImageData];
            imageView.layer.cornerRadius = imageView.frame.size.height/2;
            imageView.layer.borderWidth = 1;
            imageView.layer.masksToBounds = YES;
            imageView.layer.borderColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"green.jpg"]].CGColor;
            UILabel *nameLabel = (UILabel*)[cell viewWithTag:2];
            nameLabel.text = aUser.userName;
        }
        
        UIButton *uploadDataBt = (UIButton*)[cell viewWithTag:3];
        [uploadDataBt addTarget:self action:@selector(weiyunUpload) forControlEvents:UIControlEventTouchUpInside];
        
        UIButton *downloadDataBt = (UIButton*)[cell viewWithTag:4];
        [downloadDataBt addTarget:self action:@selector(weiyunDownload) forControlEvents:UIControlEventTouchUpInside];
        
        cell.layer.cornerRadius = 10;
        cell.layer.borderWidth = 1.2;
        return cell;
    }
    static NSString *CellIdentifier = @"Cell1";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    UILabel *label = (UILabel*)[cell viewWithTag:1];
    label.text = [self.tableList objectAtIndex:indexPath.row];
    
    
    UISwitch *swithView = (UISwitch*)[cell viewWithTag:2];
    [swithView addTarget:self action:@selector(settingPassWord:) forControlEvents:UIControlEventValueChanged];
    [swithView setHidden:YES];
    if (indexPath.row == 2) {
        swithIndexPath = indexPath;
        BOOL isPatternSet = ([[NSUserDefaults standardUserDefaults] valueForKey:kCurrentPattern]) ? YES: NO;
        [swithView setOn:isPatternSet animated:YES];
        [swithView setHidden:NO];
    }
    
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 136;
    }
    return 44;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0 && indexPath.section == 0) {
        [self login];
    }
    if (indexPath.row == 0 && indexPath.section == 1) {
        [self performSegueWithIdentifier:@"setting2type" sender:self];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //选中后的反显颜色即刻消失 一切操作结束才取消反映色
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
//    NSIndexPath *indexPath = [self.tableView cellForRowAtIndexPath:sender];
//    if (indexPath.row == 0 && indexPath.section == 1) {
//        [self performSegueWithIdentifier:@"setting2type" sender:self];
//    }
    NSObject *objc = [segue destinationViewController];
    
    if ([segue.identifier isEqualToString:@"setting2type"]) {
        NSMutableArray *list = [[DatabaseManager shareManager]showAllBillType:YES];
        [list addObjectsFromArray:[[DatabaseManager shareManager]showAllBillType:NO]];
        [objc setValue:list forKey:@"billTypeList"];
    }
}

//TODO:>>>>>>>>>
- (void)login
{
    
    time_t currentTime;
    time(&currentTime);
    
    if ((currentTime - loginTime) > 2)
    {
        NSArray *permissions = [NSArray arrayWithObjects:@"all", nil];
        [[[sdkCall getinstance] oauth] authorize:permissions inSafari:NO];
        
        loginTime = currentTime;
    }
}
#pragma mark message
- (void)loginSuccessed
{
    if (NO == _isLogined)
    {
        _isLogined = YES;
    }
    NSLog(@"登录成功");
    [self getInfo];
//    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"结果" message:@"登录成功" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
//    [alertView show];
    
//    NSArray *arrayCell = [[self tableView] visibleCells];
//    for (id cell in arrayCell)
//    {
//        [[cell textLabel] setEnabled:_isLogined];
//    }
}

- (void)loginFailed
{
    [self.navigationController popViewControllerAnimated:YES];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"结果" message:@"登录失败" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
    [alertView show];
}
- (void)getInfo
{
    if (NO == [[[sdkCall getinstance] oauth] getUserInfo])
    {
        [sdkCall showInvalidTokenOrOpenIDMessage];
    };
}
- (void)analysisResponse:(NSNotification *)notify
{
    if (notify)
    {
        APIResponse *response = [[notify userInfo] objectForKey:kResponse];
        if (URLREQUEST_SUCCEED == response.retCode && kOpenSDKErrorSuccess == response.detailRetCode)
        {
            User *aUser = [[DatabaseManager shareManager]showUser];
            if (aUser == nil) {
                aUser = [[User alloc]init];
                aUser.userID = @(1);
                aUser.userName = [response.jsonResponse objectForKey:@"nickname"];
                [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[response.jsonResponse objectForKey:@"figureurl_2"]]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                    aUser.userImageData = data;
                    [[DatabaseManager shareManager]addNewUser:aUser];
                    [self.iTableView reloadData];
                }];
            }
            else{
                aUser = [[User alloc]init];
                aUser.userID = @(1);
                aUser.userName = [response.jsonResponse objectForKey:@"nickname"];
                [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[response.jsonResponse objectForKey:@"figureurl_2"]]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                    aUser.userImageData = data;
                    [[DatabaseManager shareManager]ModifUser:aUser];
                    [self.iTableView reloadData];
                }];
            }
        }
        else
        {
            NSString *errMsg = [NSString stringWithFormat:@"errorMsg:%@\n%@", response.errorMsg, [response.jsonResponse objectForKey:@"msg"]];
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"操作失败" message:errMsg delegate:self cancelButtonTitle:@"我知道啦" otherButtonTitles: nil];
            [alert show];
        }
    }
}
//TODO:微云
- (void)weiyunUpload{
    _iCurrentType = kWeiyunDelRecord;
    if (YES == _isLogined) {
        [self.activityView setHidden:NO];
        [self.activityView startAnimating];
        self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.hud.labelText = NSLocalizedString(@"上传数据中...", @"");
    }
    [self weiyunUpload:@(2)];
    
    
}
- (void)weiyunDownload{
    [[DatabaseManager shareManager] closeDataBase];
    _iCurrentType = kWeiyunDownload;
    if (YES == _isLogined) {
        
        [self.activityView setHidden:NO];
        [self.activityView startAnimating];
        isDownload = YES;
        [self weiyunDownload:@(2)];
        self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.hud.labelText = NSLocalizedString(@"下载数据中...", @"");
    }
    [self weiyunDownload:@(2)];
    
}
- (void)weiyunUpload:(NSNumber *)weiyunType
{
    WeiYun_upload_photo_GET *request = nil;
    NSData *data = nil;
    NSUInteger type = [weiyunType unsignedIntegerValue];
    switch (type)
    {
        case kWeiyunPhoto:
        {
            ipc = [[UIImagePickerController alloc] init];
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
                ipc.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;
                if (kWeiyunPhoto == type)
                {
                    isImagePic=true;
                    ipc.mediaTypes = [NSArray arrayWithObjects:(NSString *)kUTTypeImage, nil];
                }
                else if (kWeiyunVideo == type)
                {
                    ipc.mediaTypes = [NSArray arrayWithObjects:@"public.movie",nil];
                }
                
            }
            ipc.delegate = self;
            if (uploadPic_ipc)
            {
                __RELEASE(uploadPic_ipc);
                uploadPic_ipc = nil;
            }
            uploadPic_ipc = __RETAIN(ipc);
            if ([[[UIDevice currentDevice] systemVersion] floatValue] > 5.0)
            {
                [self presentViewController:ipc animated:YES completion:nil];
            }
            else
            {
                [self presentModalViewController:ipc animated:YES];
            }
            return;
        }
        case kWeiyunVideo:
        {
            NSString *videoPath = [self iBillFileDBPath];
            data = [[NSData alloc] initWithContentsOfFile:videoPath];
            request = [[WeiYun_upload_video_GET alloc] init];
            [self sendWeiyunUploadRequest:request data:data fileSuffix:@"mov"];
        }
            break;
        case kWeiyunMusic:
        {
            NSString *audioPath = [NSString stringWithFormat:@"%@/testaudio.mp3", [[NSBundle mainBundle] resourcePath]];
            data = [[NSData alloc] initWithContentsOfFile:audioPath];
            request = [[WeiYun_upload_music_GET alloc] init];
            [self sendWeiyunUploadRequest:request data:data fileSuffix:@"mp3"];
        }
            break;
        default:
            break;
    }
    
    
}
- (void)weiyunDownload:(NSNumber *)weiyunType
{
    
    NSUInteger type = [weiyunType unsignedIntegerValue];
    [self weiyunGetList:[NSNumber numberWithInteger:type]];

}
- (void)weiyunGetList:(NSNumber *)weiyunType
{
    NSUInteger type = [weiyunType unsignedIntegerValue];
    WeiYun_get_photo_list_GET *request = nil;
    switch (type)
    {
        case kWeiyunPhoto:
            request = [[WeiYun_get_photo_list_GET alloc] init];
            break;
        case kWeiyunMusic:
            request = [[WeiYun_get_music_list_GET alloc] init];
            break;
        case kWeiyunVideo:
            request = [[WeiYun_get_video_list_GET alloc] init];
            break;
        default:
            break;
    }
    
    request.param_number = @"100";
    request.param_offset = @"0";
    [self sendCgiRequest:request];
    isGetList=true;
}
- (void)sendWeiyunUploadRequest:(WeiYun_upload_photo_GET *)request data:(NSData *)data fileSuffix:(NSString *)fileSuffix
{
    request.param_sha = [self digest:data];
    request.param_md5 = [self md5:data];
    
    //[self inputStr:@"输入文件名"];
    
    if(isStop){
        /*
        if(0 == [_inputStr length])
        {
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"HH_mm_ss"];
            NSString *name = [dateFormatter stringFromDate:[NSDate date]];
            request.param_name = [NSString stringWithFormat:@"%@.%@",name, fileSuffix];
            __RELEASE(dateFormatter);
        }
        else
        {
            request.param_name = [NSString stringWithFormat:@"%@.%@",_inputStr, fileSuffix];
        }*/
        NSString *fliename = [kBillSqlitedbKey stringByReplacingOccurrencesOfString:@".db" withString:@""];
        request.param_name = [NSString stringWithFormat:@"%@.mov",fliename];
        request.param_size = [NSString stringWithFormat:@"%u", [data length]];
        request.param_upload_type = @"control";
        request.paramUploadData = data;
        
        [self sendCgiRequest:request];
    }
    
}
- (void)sendCgiRequest:(TCAPIRequest *)request
{
    if(NO == [[[sdkCall getinstance]oauth] sendAPIRequest:request callback:self])
    {
        [sdkCall showInvalidTokenOrOpenIDMessage];
    }
    else
    {
        [_arrCgiRequest addObject:request];
    }
}
//TODO:微云编码》》》》》》
- (NSString*)stringWithHexBytes2:(NSData*)data
{
    static const char hexdigits[] = "0123456789ABCDEF";
    const size_t numBytes = [data length];
    const unsigned char* bytes = [data bytes];
    char *strbuf = (char *)malloc(numBytes * 2 + 1);
    char *hex = strbuf;
    NSString *hexBytes = nil;
    
    for (int i = 0; i<numBytes; ++i)
    {
        const unsigned char c = *bytes++;
        *hex++ = hexdigits[(c >> 4) & 0xF];
        *hex++ = hexdigits[(c ) & 0xF];
    }
    *hex = 0;
    hexBytes = [NSString stringWithUTF8String:strbuf];
    free(strbuf);
    return hexBytes;
}
- (NSString*) stringWithHexBytes1:(NSData*)data
{
    NSMutableString *stringBuffer = [NSMutableString stringWithCapacity:([data length] * 2)];
    const unsigned char *dataBuffer = [data bytes];
    
    for (int i = 0; i < [data length]; ++i)
    {
        [stringBuffer appendFormat:@"%02x", (unsigned int)dataBuffer[i]];
    }
    return __AUTORELEASE([stringBuffer copy]);
}

-(NSString *)digest:(NSData*)data
{
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1([data bytes], [data length], digest);
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
    {
        [output appendFormat:@"%02x", digest[i]];
    }
    
    return output;
}

-(NSString *)md5:(NSData*)data
{
    unsigned char result[16];
    CC_MD5(data.bytes, data.length, result);
    return [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7], result[8],
            result[9], result[10], result[11], result[12], result[13], result[14], result[15]];
}

-(NSData *)dataFromHex16String:(NSString *)hex16Str
{
    NSString *hexString=[[hex16Str uppercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([hexString length]%2!=0) {
        return nil;
    }
    Byte tempbyt[1]={0};
    NSMutableData* bytes=[NSMutableData data];
    for(int i=0;i<[hexString length];i++)
    {
        unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
        int int_ch1 = 0;
        if(hex_char1 >= '0' && hex_char1 <='9')
            int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
        else
            return nil;
        i++;
        
        unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
        int int_ch2 = 0;
        if(hex_char2 >= '0' && hex_char2 <='9')
            int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
        else if(hex_char2 >= 'A' && hex_char2 <='F')
            int_ch2 = hex_char2-55; //// A 的Ascll - 65
        else
            return nil;
        
        tempbyt[0] = int_ch1+int_ch2;  ///将转化后的数放入Byte数组里
        [bytes appendBytes:tempbyt length:1];
    }
    return bytes;
}
//TODO:文件
- (void)getFileInfoList:(TCAPIRequest *)request didResponse:(APIResponse *)response
{
    NSDictionary *data = [[response jsonResponse] objectForKey:@"data"];
    NSArray *content = [data objectForKey:@"content"];
    NSUInteger fileTotal = [[data objectForKey:@"file_total"] unsignedIntegerValue];
    if (0 == fileTotal)
    {
        content = nil;
    }
    
    if ([request isMemberOfClass:[WeiYun_get_photo_list_GET class]])
    {
        if (_picFileId)
        {
            __RELEASE(_picFileId);
        }
        
        _picFileId = [content copy];
    }
    else if([request isMemberOfClass:[WeiYun_get_video_list_GET class]])
    {
        if (_videoFileId)
        {
            __RELEASE(_videoFileId);
        }
        
        _videoFileId = [content copy];
        
    }
    else if([request isMemberOfClass:[WeiYun_get_music_list_GET class]])
    {
        if (_audioFileId)
        {
            __RELEASE(_audioFileId);
        }
        
        _audioFileId = [content copy];
    }
    
//    [_weiyunFileIdListViewController setArrFileInfo:content];
//    [[_weiyunFileIdListViewController tableView] reloadData];
}
- (NSString *)responseDataProcess:(TCAPIRequest *)request didResponse:(APIResponse *)response
{
    
    if([request isKindOfClass:[WeiYun_get_photo_list_GET class]])
    {
        [self getFileInfoList:request didResponse:response];
    }
    
    if ([request isKindOfClass:[WeiYun_query_all_record_GET class]])
    {
        if (_allRecord)
        {
            __RELEASE(_allRecord);
        }
        
        NSDictionary *data = [[response jsonResponse] objectForKey:@"data"];
        NSUInteger count = [[data objectForKey:@"count"] unsignedIntegerValue];
        NSArray *keys = [data objectForKey:@"keys"];
        if (0 != count)
        {
            _allRecord = [[NSMutableArray alloc] initWithCapacity:[keys count]];
            for (id key in keys)
            {
                NSData *data = [self dataFromHex16String:[key objectForKey:@"key"]];
                NSString *resStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                [_allRecord addObject:@{@"key":resStr}];
            }
            
//            [_weiyunFileIdListViewController setArrFileInfo:_allRecord];
//            [[_weiyunFileIdListViewController tableView] reloadData];
            
        }
    }
    
    if ([request isKindOfClass:[WeiYun_download_video_GET class]])
    {
        if (NO == [self saveFileData:request didResponse:response])
        {
            return @"本地保存文件失败，重新下载。";
        }
        else
        {
            /*
            NSFileManager *manager = [NSFileManager defaultManager];
            NSString *toPath = [NSString stringWithFormat:@"%@/Documents/SqlBillNote2.mov",NSHomeDirectory()];
            [manager createDirectoryAtPath:[toPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
            NSError *error;
            NSString *filePath = [NSString stringWithFormat:@"%@/Documents/data/SqlBillNote.mov",NSHomeDirectory()];
            BOOL isSuccess = [manager moveItemAtPath:filePath toPath:toPath error:&error];
            if (isSuccess == YES) {
                NSLog(@"yes");
            }
            else{
                NSLog(@"%@",error);
            }*/
            [self.activityView setHidden:YES];
            [self.activityView stopAnimating];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            self.hud = nil;
            return @"本地文件保存成功。";
            
        }
    }
    
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:1];
    if ([request isKindOfClass:[WeiYun_check_record_GET class]])
    {
        [array addObject:@"key"];
    }
    
    NSMutableString *str=[NSMutableString stringWithFormat:@""];
    for (id key in response.jsonResponse)
    {
        
        if ([array containsObject:key])
        {
            NSData *data = [self dataFromHex16String:[response.jsonResponse objectForKey:key]];
            NSString *resStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            [str appendString: [NSString stringWithFormat:@"%@:%@\n",key,resStr]];
        }
        else if([key isKindOfClass:[NSString class]]
                && [key isEqualToString:@"data"]
                &&([request isKindOfClass:[WeiYun_query_all_record_GET class]]
                   ||[request isKindOfClass:[WeiYun_get_record_GET class]]))
        {
            NSDictionary *jsonData = [response.jsonResponse objectForKey:key];
            if([request isKindOfClass:[WeiYun_query_all_record_GET class]])
            {
                
                NSArray *keys = [jsonData objectForKey:@"keys"];
                NSUInteger count = [[[response jsonResponse] objectForKey:@"count"] unsignedIntegerValue];
                if (0 != count)
                {
                    for(id keyValue in keys)
                    {
                        NSData *data = [self dataFromHex16String:[keyValue objectForKey:@"key"]];
                        NSString *resStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                        [str appendString: [NSString stringWithFormat:@"key = %@\n", resStr]];
                    }
                }
            }
            else if([request isKindOfClass:[WeiYun_get_record_GET class]])
            {
                NSData *data = [self dataFromHex16String:[jsonData objectForKey:@"value"]];
                NSString *resStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                [str appendString: [NSString stringWithFormat:@"value = %@\n", resStr]];
            }
        }
        else
        {
            NSString *result = [response.jsonResponse objectForKey:key];
            [str appendString: [NSString stringWithFormat:@"%@:%@\n",key,result]];
        }
    }
    
    
    
    return str;
}
- (BOOL)saveFileData:(TCAPIRequest *)request didResponse:(APIResponse *)response
{
    if (NO == [request isKindOfClass:[WeiYun_download_photo_GET class]])
    {
        return NO;
    }
    
    NSData *data = [[response jsonResponse] objectForKey:@"data"];
    if (nil == data)
    {
        return NO;
    }
    
    NSFileManager *mgr = [NSFileManager defaultManager];
    //NSString *dirName = nil;
    /*
    if ([request isMemberOfClass:[WeiYun_download_photo_GET class]])
    {
        dirName = @"photo";
    }
    else if ([request isMemberOfClass:[WeiYun_download_video_GET class]])
    {
        dirName = @"Data";
    }
    else if ([request isMemberOfClass:[WeiYun_download_music_GET class]])
    {
        dirName = @"music";
    }
    */
    NSString *dirPath = [NSString stringWithFormat:@"%@/Documents",NSHomeDirectory()];
    
    BOOL isDir = YES;
    if (NO == [mgr fileExistsAtPath:dirPath isDirectory:&isDir])
    {
        if (NO == [mgr createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil])
        {
            return NO;
        }
    }
    
    NSString *fileName = [request paramUserData];
    if (nil == fileName)
    {
        fileName = [(WeiYun_download_photo_GET *)request param_file_id];
    }
    fileName = [fileName stringByReplacingOccurrencesOfString:@".mov" withString:@".db"];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@",dirPath, fileName];
    
    if ([request isMemberOfClass:[WeiYun_download_photo_GET class]])
    {
        [self getPicFromResponse:request didResponse:response];
    }
    return [data writeToFile:filePath atomically:YES];
}
- (BOOL)getPicFromResponse:(TCAPIRequest *)request didResponse:(APIResponse *)response
{
    if (NO == [request isMemberOfClass:[WeiYun_download_photo_GET class]]
        && NO == [request isMemberOfClass:[WeiYun_get_photo_thumb_GET class]])
    {
        return NO;
    }
    
    NSData *data = [[response jsonResponse] objectForKey:@"data"];
    UIImage *image = [UIImage imageWithData:data];
    if (nil != image)
    {
        UIImage *thumbImage = [UIImage imageWithCGImage:[image CGImage] scale:0.4f orientation:UIImageOrientationUp];
        if (nil != image)
        {
            [[[sdkCall getinstance] photos] addObject:image];
        }
        
        if (nil != thumbImage)
        {
            [[[sdkCall getinstance] thumbPhotos] addObject:thumbImage];
        }
        
        /*
        if (_localGallery)
        {
            [_localGallery dismissModalViewControllerAnimated:NO];
            __RELEASE(_localGallery);
        }
        
        _localGallery = [[FGalleryViewController alloc] initWithPhotoSource:[sdkCall getinstance]];
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:_localGallery];
        __RELEASE(_localGallery);
        */
        /*
        if([[[UIDevice currentDevice] systemVersion] floatValue] >= 5.0)
        {
            [self presentViewController:navigationController animated:YES completion:nil];
        }
        else
        {
            [self presentModalViewController:navigationController animated:YES];
        }
        
        __RELEASE(navigationController);
         */
        return YES;
    }
    
    return NO;
}
- (NSString *)responseErrMsgProcess:(TCAPIRequest *)request didResponse:(APIResponse *)response
{
    if ([request isKindOfClass:[WeiYun_BaseRequest class]])
    {
        NSNumber *retCode = [response.jsonResponse objectForKey:@"ret"];
        NSString *errMsg = nil;
        switch ([retCode unsignedIntegerValue])
        {
            case 200001:
                errMsg = @"输入参数无效";
                break;
            case 201020:
                errMsg = @"文件不存在";
                break;
            case 201022:
                errMsg = @"文件已经存在";
                break;
            case 201029:
                errMsg = @"单个文件大小超限";
                break;
            case 201051:
                errMsg = @"当前目录下已经存在同名文件";
                break;
            case 230032:
                errMsg = @"key长度无效";
                break;
            case 230033:
                errMsg = @"data长度无效";
                break;
            case 230034:
                errMsg = @"key不存在";
                break;
            default:
                errMsg = [NSString stringWithFormat:@"%@", retCode];
                break;
        }
        return errMsg;
    }
    
    NSString *errMsg = [NSString stringWithFormat:@"errorMsg:%@\n%@", response.errorMsg, [response.jsonResponse objectForKey:@"msg"]];
    return errMsg;
}
//TODO:llll
-(NSString *)iBillFileDBPath{
    NSArray *dirList = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);//找到保存路径
    NSString *filePath=dirList[0];//将数组转化为字符串对象
    if (!filePath) {
        return nil;
    }
    NSString *path = [filePath stringByAppendingPathComponent:kBillSqlitedbKey];//将文件名添加到filePath对象所指的路径下
    return path;
    
}

#pragma mark weiyunFileIdListDelegate
- (void)weiyunFileIdSelectedFileIdfileInfo:(NSDictionary *)fileInfo  andType:(WeiyunListType)contentType withDownlType:(WeiyunOperationType)operateType;
{
    if (contentType == kWeiyunListRecord)
    {
        WeiYun_check_record_GET *request = nil;
        if (operateType == kWeiyunGetRecord)
        {
            request = [[WeiYun_get_record_GET alloc] init];
            
        }
        else if(operateType == kWeiyunDelRecord)
        {
            request = [[WeiYun_delete_record_GET alloc] init];
        }
        
        NSString *key = [self stringWithHexBytes2:[[fileInfo objectForKey:@"key"] dataUsingEncoding:NSUTF8StringEncoding]];
        request.param_key = key;
        [self sendCgiRequest:request];
    }
    else
    {
        NSString *file_id = [fileInfo objectForKey:@"file_id"];
        NSString *file_name = [fileInfo objectForKey:@"file_name"];
        
        NSArray *weiyunClass = [_weiyunOperateArray objectAtIndex:operateType];
        Class class = [weiyunClass objectAtIndex:contentType];
        
        WeiYun_BaseRequest *request = [[class alloc] init];
        [request performSelector:@selector(setParam_file_id:) withObject:file_id];
        [request setParamUserData:file_name];
        if ([request isMemberOfClass:[WeiYun_get_photo_thumb_GET class]])
        {
            [request performSelector:@selector(setParam_thumb:) withObject:@"64*64"];
        }
        [self sendCgiRequest:request];
        
        if([request isKindOfClass:[WeiYun_download_video_GET class]]
           || [request isKindOfClass:[WeiYun_get_photo_thumb_GET class]])
        {
            [_progressView setProgress:0];
            [_progressView setHidden:NO];
            
            //[[self navigationController] popViewControllerAnimated:YES];
        }
        isUpload = YES;
    }
}


#pragma mark cgiRequestDelegate
- (void)cgiRequest:(TCAPIRequest *)request didResponse:(APIResponse *)response
{
    if (URLREQUEST_SUCCEED == response.retCode && kOpenSDKErrorSuccess == response.detailRetCode)
    {
        NSString *str = [self responseDataProcess:request didResponse:response];
    
        if (isDownload == YES) {
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:[response.message dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil];
            NSLog(@"开始下载");
            dic = [dic objectForKey:@"data"];
            
            NSInteger count = [[dic objectForKey:@"file_total"] integerValue];
            if(count != 0){
                NSArray *array = [dic objectForKey:@"content"];
                for (NSDictionary *iDic in array) {
                    NSString *str = [iDic objectForKey:@"file_name"];
                    if ([str isEqualToString:@"SqlBillNote.mov"]) {
                        self.fileDictoinary = iDic;
                        [self weiyunFileIdSelectedFileIdfileInfo:iDic andType:kWeiyunListVideo withDownlType:kWeiyunDownload];
                        
                    }
                }
                
            }
            else{
                UIAlertView *alc = [[UIAlertView alloc]initWithTitle:@"错误提示" message:@"亲：没有数据啊！" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alc show];
            }
            
            isDownload = NO;
        }
        else if (isDelete == YES) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:[response.message dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil];
            NSLog(@"开始删除");
            dic = [dic objectForKey:@"data"];
            NSArray *array = [dic objectForKey:@"content"];
            for (NSDictionary *iDic in array) {
                if ([[iDic objectForKey:@"file_name"] isEqualToString:@"SqlBillNote.mov"]) {
                    self.fileDictoinary = iDic;
                    _iCurrentType = kWeiyunDelete;
                    [self weiyunFileIdSelectedFileIdfileInfo:iDic andType:kWeiyunListVideo withDownlType:kWeiyunDelete];
                    
                }
            }
            isDelete = NO;
            
        }
        else{
            NSLog(@"成功：%@",str);
            if (_iCurrentType == kWeiyunDelRecord) {
                //TODO:上传成功
                NSLog(@"上传成功：%@",str);
                [self.activityView setHidden:YES];
                [self.activityView stopAnimating];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                
                self.hud = nil;
            }
            else if (_iCurrentType == kWeiyunDelete) {
                NSLog(@"删除成功：%@",str);
                _iCurrentType = kWeiyunDelRecord;
                [self weiyunUpload:@(2)];
            }
            
            else{
                
            }
        }
        
        
        
        if ([request isKindOfClass:[WeiYun_upload_photo_GET class]])
        {
            WeiYun_get_photo_list_GET *request = nil;
            if ([request isMemberOfClass:[WeiYun_upload_photo_GET class]])
            {
                request = [[WeiYun_get_photo_list_GET alloc] init];
            }
            else if([request isMemberOfClass:[WeiYun_upload_music_GET class]])
            {
                request = [[WeiYun_get_music_list_GET alloc] init];
            }
            else if([request isMemberOfClass:[WeiYun_upload_video_GET class]])
            {
                request = [[WeiYun_get_video_list_GET alloc] init];
            }
            
            request.param_offset = @"0";
            request.param_number = @"200";
        }
    }
    else
    {
        NSString *errMsg = [self responseErrMsgProcess:request didResponse:response];
        NSLog(@"%@",errMsg);
        if ([errMsg isEqualToString:@"当前目录下已经存在同名文件"]) {
            isDelete = YES;
            [self weiyunGetList:@(2)];
        }
    }
    if (nil != request)
    {
        [_arrCgiRequest removeObject:request];
    }
}

- (void)cgiRequest:(TCAPIRequest *)request didSendBodyData:(long long)bytesWritten totalBytesWritten:(long long)totalBytesWritten totalBytesExpectedToWrite:(long long)totalBytesExpectedToWrite
{
    NSLog(@">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    CGFloat progress = (totalBytesWritten / totalBytesExpectedToWrite);
    [_progressView setProgress:progress animated:YES];
}

#pragma mark TCAPIRequestUploadDelegate
- (BOOL)cgiUploadRequest:(TCAPIRequest *)uploadRequest shouldBeginUploadingStorageRequest:(NSURLRequest *)storageRequest
{
    return YES;
}



#pragma mark TCAPIRequestDownloadDelegate
- (BOOL)cgiDownloadRequest:(TCAPIRequest *)downloadRequest shouldBeginDownloadingStorageRequest:(NSURLRequest *)storageRequest
{
    return YES;
}



@end
